<template>
  <div class="distribution-center">
    <div class="distribution-header">
      <div class="header-content">
        <h1>分销中心</h1>
        <p>邀请好友购买商品，赚取佣金</p>
      </div>
    </div>

    <div class="distribution-content">
      <!-- 分销员信息 -->
      <div class="distributor-info" v-if="isDistributor">
        <el-card>
          <div class="info-header">
            <el-avatar :size="60" :src="VITE_URL + '/storage/' + distributorInfo.avatar" />
            <div class="info-text">
              <h2>{{ distributorInfo.customer_name }}</h2>
              <p>分销员ID: {{ distributorInfo.id }}</p>
            </div>
          </div>
          
          <div class="info-stats">
            <div class="stat-item">
              <div class="stat-value">¥{{ distributorInfo.total_commission }}</div>
              <div class="stat-label">累计佣金</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">¥{{ distributorInfo.withdrawable_commission }}</div>
              <div class="stat-label">可提现佣金</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">¥{{ distributorInfo.frozen_commission }}</div>
              <div class="stat-label">冻结佣金</div>
            </div>
          </div>
          
          <div class="info-actions">
            <el-button type="primary" @click="handleWithdraw">申请提现</el-button>
            <el-button @click="handleQrcode">推广二维码</el-button>
          </div>
        </el-card>
      </div>
      
      <!-- 申请成为分销员 -->
      <div class="apply-distributor" v-else>
        <el-card>
          <div class="apply-content">
            <h2>申请成为分销员</h2>
            <p>成为分销员，邀请好友购买商品赚取佣金</p>
            <el-button type="primary" @click="handleApply" :loading="applying">立即申请</el-button>
          </div>
        </el-card>
      </div>
      
      <!-- 功能导航 -->
      <div class="function-nav">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="nav-card" @click="goToCommissions">
              <div class="nav-content">
                <i class="el-icon-tickets"></i>
                <div class="nav-text">
                  <h3>佣金记录</h3>
                  <p>查看佣金明细</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="nav-card" @click="goToTeam">
              <div class="nav-content">
                <i class="el-icon-user"></i>
                <div class="nav-text">
                  <h3>我的团队</h3>
                  <p>查看推广团队</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="nav-card" @click="goToOrders">
              <div class="nav-content">
                <i class="el-icon-shopping-cart-2"></i>
                <div class="nav-text">
                  <h3>推广订单</h3>
                  <p>查看推广订单</p>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 提现申请对话框 -->
      <el-dialog
        v-model="withdrawDialogVisible"
        title="申请提现"
        width="500px"
      >
        <el-form
          :model="withdrawForm"
          :rules="withdrawRules"
          ref="withdrawFormRef"
          label-width="100px"
        >
          <el-form-item label="提现金额" prop="amount">
            <el-input-number
              v-model="withdrawForm.amount"
              :min="0"
              :precision="2"
              :step="100"
              style="width: 100%"
            />
            <div style="margin-top: 5px; color: #999; font-size: 12px;">
              可提现金额：¥{{ distributorInfo.withdrawable_commission }}
            </div>
          </el-form-item>
          <el-form-item label="提现方式" prop="method">
            <el-select v-model="withdrawForm.method" placeholder="请选择提现方式" style="width: 100%">
              <el-option label="微信" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="银行卡" value="bank" />
            </el-select>
          </el-form-item>
          <el-form-item label="账号信息" prop="account_info">
            <el-input
              v-model="withdrawForm.account_info"
              type="textarea"
              placeholder="请输入账号信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="withdrawDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitWithdraw" :loading="withdrawSaving">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 推广二维码对话框 -->
      <el-dialog
        v-model="qrcodeDialogVisible"
        title="推广二维码"
        width="400px"
      >
        <div class="qrcode-content">
          <div class="qrcode-image">
            <!-- TODO: 显示推广二维码 -->
            <div style="width: 200px; height: 200px; background: #f5f5f5; display: flex; align-items: center; justify-content: center;">
              二维码区域
            </div>
          </div>
          <div class="qrcode-info">
            <p>扫描二维码，邀请好友注册购买</p>
            <el-button type="primary" @click="copyInviteLink">复制邀请链接</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const VITE_URL = (window as any).VITE_URL
const router = useRouter()

// 分销员状态
const isDistributor = ref(false)
const distributorInfo = ref({
  id: 0,
  customer_id: 0,
  customer_name: '',
  telephone: '',
  avatar: '',
  level: 1,
  total_commission: 0,
  withdrawable_commission: 0,
  frozen_commission: 0,
  status: 1,
  create_time: ''
})

// 申请相关
const applying = ref(false)

// 提现相关
const withdrawDialogVisible = ref(false)
const withdrawSaving = ref(false)
const withdrawForm = ref({
  amount: 0,
  method: 'wechat',
  account_info: ''
})
const withdrawFormRef = ref()
const withdrawRules = {
  amount: [{ required: true, message: '请输入提现金额', trigger: 'blur' }],
  method: [{ required: true, message: '请选择提现方式', trigger: 'change' }],
  account_info: [{ required: true, message: '请输入账号信息', trigger: 'blur' }]
}

// 二维码相关
const qrcodeDialogVisible = ref(false)

// 申请成为分销员
const handleApply = async () => {
  try {
    applying.value = true
    const url = `${VITE_URL}/distribution.apply`
    const res = await axios.post(url)
    if (res.data.status === 0) {
      ElMessage.success('申请成功')
      getDistributorInfo()
    } else {
      ElMessage.error(res.data.message || '申请失败')
    }
  } catch (error) {
    ElMessage.error('申请失败')
  } finally {
    applying.value = false
  }
}

// 获取分销员信息
const getDistributorInfo = async () => {
  try {
    const url = `${VITE_URL}/distribution.info`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      isDistributor.value = true
      distributorInfo.value = res.data.data
    } else {
      isDistributor.value = false
    }
  } catch (error) {
    isDistributor.value = false
  }
}

// 申请提现
const handleWithdraw = () => {
  withdrawForm.value.amount = 0
  withdrawForm.value.method = 'wechat'
  withdrawForm.value.account_info = ''
  withdrawDialogVisible.value = true
}

// 提交提现申请
const submitWithdraw = async () => {
  try {
    await withdrawFormRef.value.validate()
    
    withdrawSaving.value = true
    const url = `${VITE_URL}/distribution.withdraw`
    const res = await axios.post(url, withdrawForm.value)
    if (res.data.status === 0) {
      ElMessage.success('申请成功')
      withdrawDialogVisible.value = false
      getDistributorInfo()
    } else {
      ElMessage.error(res.data.message || '申请失败')
    }
  } catch (error) {
    ElMessage.error('申请失败')
  } finally {
    withdrawSaving.value = false
  }
}

// 推广二维码
const handleQrcode = () => {
  qrcodeDialogVisible.value = true
}

// 复制邀请链接
const copyInviteLink = () => {
  // TODO: 实现复制邀请链接功能
  ElMessage.success('链接已复制到剪贴板')
}

// 跳转到佣金记录
const goToCommissions = () => {
  router.push('/distribution/commissions')
}

// 跳转到团队管理
const goToTeam = () => {
  router.push('/distribution/team')
}

// 跳转到推广订单
const goToOrders = () => {
  router.push('/distribution/orders')
}

onMounted(() => {
  getDistributorInfo()
})
</script>

<style scoped>
.distribution-center {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.distribution-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.header-content h1 {
  font-size: 32px;
  margin-bottom: 10px;
}

.header-content p {
  font-size: 16px;
  opacity: 0.9;
}

.distributor-info .info-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.info-text {
  margin-left: 20px;
}

.info-text h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.info-text p {
  margin: 0;
  color: #666;
}

.info-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
}

.stat-label {
  color: #999;
}

.info-actions {
  text-align: center;
}

.apply-content {
  text-align: center;
  padding: 40px 20px;
}

.apply-content h2 {
  margin-bottom: 20px;
}

.apply-content p {
  color: #666;
  margin-bottom: 30px;
}

.function-nav {
  margin-top: 30px;
}

.nav-card {
  cursor: pointer;
  transition: all 0.3s;
}

.nav-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.nav-content {
  display: flex;
  align-items: center;
}

.nav-content i {
  font-size: 32px;
  color: #667eea;
  margin-right: 15px;
}

.nav-text h3 {
  margin: 0 0 5px 0;
}

.nav-text p {
  margin: 0;
  color: #999;
}

.qrcode-content {
  text-align: center;
}

.qrcode-image {
  margin-bottom: 20px;
}

.qrcode-info p {
  margin-bottom: 20px;
  color: #666;
}
</style>